<template>
	<view>
		<view class="flex justify-between margin-sm">
			<view class="cuIcon-refresh text-gray text-lg" @tap="listLinkageTrigger()"><text
					class="margin-left-xs">{{$t('trigger')}}</text></view>
			<view class="flex margin-right">
				<view class="cuIcon-add" :style="{color : themeConfig.primaryColor}" @tap="showAdd">
					{{$t('add')}}
				</view>
				<view class="cuIcon-check margin-left-sm"
					:style="{color : haveChange?themeConfig.primaryColor:'#aaaaaa'}" @tap="save">
					{{$t('save')}}
				</view>
			</view>
		</view>
		<view v-for="(trigger,index) in triggerList" :key="index"
			style="height: 80px;"
			class="bg-white padding-sm margin-sm flex justify-between align-center common-box" @tap="edit(trigger)">
			<view v-if="trigger.type === 't'" class=" flex align-center">
				<view class="margin-sm cuIcon-countdown" style="font-size: 20px;"></view>
				<view>
					<view class="text-bold text-lg">{{$t('time')}}</view>
					<view class="text-gray margin-top-xs text-sm">{{trigger.timer}}</view>
				</view>
			</view>
			<view v-else-if="trigger.type === 't2'" class=" flex align-center">
				<view class="margin-sm cuIcon-countdown" style="font-size: 20px;"></view>
				<view>
					<view class="text-bold text-lg">{{$t('timeSlot')}}</view>
					<view class="text-gray margin-top-xs ">{{trigger.timer}}</view>
				</view>
			</view>
			<view v-else-if="trigger.type === 'i'" class=" flex align-center">
				<view class="margin-sm cuIcon-countdown" style="font-size: 20px;"></view>
				<view>
					<view class="text-bold text-lg">{{$t('interval')}}</view>
					<view class="text-gray margin-top-xs text-sm">{{trigger.timer}}</view>
				</view>
			</view>
			<view v-else-if="trigger.type === 's'" class=" flex align-center">
				<image :src="trigger.iconUrl" style="width: 20px;height: 20px;" class="margin-sm"></image>
				<view>
					<view class="text-lg">
						<text class="text-bold margin-right-sm ">{{formatSensorType(trigger.sensorType)}}{{$t('port')}}:{{trigger.port}}</text>
						<text v-if="trigger.sensorName">[{{trigger.sensorName}}]</text>
					</view>
					<view class="text-gray margin-top-xs text-sm">
						<text>{{ trigger.name }}</text>
						<text class="margin-left-xs">
							{{ formatterLogic(trigger.logic) }}
						</text>
						<text class="margin-left-xs">{{trigger.rawValue}}</text>
					</view>
				</view>
			</view>
			<view v-else>{{$t('unKnow')}}</view>
			<view  class="flex">
				<view class="cuIcon-delete text-pink margin-right-sm" @tap.stop="deleteItem(index)"></view>
			</view>
		</view>

		<view class="cu-modal bottom-modal" :class="editDialog?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-gray" @tap="editDialog = false">{{$t('cancel')}}</view>
					<view class="action" :style="{color : themeConfig.primaryColor}" @tap="editSave">{{$t('confirm')}}
					</view>
				</view>
				<view>
					<form>
						<view class="cu-form-group">
							<view class="title">{{$t('type')}}</view>
							<view class='flex'>
								<view class="margin-right-sm" v-for="(item,index) in typeList" :key="index"
									@tap="typeChange(item)">
									<view v-if="item.value === trigger.type" class='cu-tag'
										:class="'bg-' + themeConfig.theme">
										{{item.label}}
									</view>
									<view v-else class='cu-tag' :class="'line-' + themeConfig.theme">
										{{item.label}}
									</view>
								</view>
							</view>
						</view>
						<view class="cu-form-group" v-if="trigger.type === 't'">
							<view class="title">{{$t('time')}}</view>
							<picker mode="time" :value="trigger.timer" @change="timerChange">
								<text class="text-sm">{{trigger.timer}}</text>
							</picker>
						</view>
						<view class="cu-form-group" v-else-if="trigger.type === 't2'">
							<view class="title">{{$t('timeSlot')}}</view>
							<picker mode="multiSelector" :value="timeSlotMultiIndex" :range="timeSlotMultiArray"
								@change="timerSlotChange">
								<text class="text-sm">{{trigger.timer}}</text>
							</picker>
						</view>
						<view class="cu-form-group" v-else-if="trigger.type === 'i'">
							<view class="title">{{$t('interval')}}</view>
							<picker mode="time" :value="trigger.timer" @change="timerChange">
								<text class="text-sm">{{trigger.timer}}</text>
							</picker>
						</view>
						<view v-else-if="trigger.type === 's'">
							<view class="cu-form-group">
								<view class="title">{{$t('sensor')}}</view>
								<picker mode="multiSelector" @columnchange="explainMultiColumnChange"
									@change="explainMultiChange" :value="explainMultiIndex" :range="explainMultiArray">
									<view class="picker text-sm">
										{{explainMultiArray[0][explainMultiIndex[0]]}}，{{explainMultiArray[1][explainMultiIndex[1]]}}
									</view>
								</picker>
							</view>
							<view class="cu-form-group">
								<view class="title">{{$t('logic')}}</view>
								<view class="flex">
									<view class="margin-right-sm" v-for="(item,index) in logicList" :key="index"
										@tap="logicChange(item)">
										<view v-if="item.value === trigger.logic" class='cu-tag'
											:class="'bg-' + themeConfig.theme">
											{{item.label}}
										</view>
										<view v-else class='cu-tag' :class="'line-' + themeConfig.theme">
											{{item.label}}
										</view>
									</view>
								</view>
							</view>
							<view class="cu-form-group">
								<view class="title">{{$t('value')}}</view>
								<input v-model="trigger.rawValue" />
							</view>
						</view>
					</form>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		showToast
	} from '@/util/toast.js'
	import *
	as deviceSensorApi from '@/api/iot/iotDeviceSensorApi.js'
	import *
	as deviceLinkageTriggerApi from '@/api/iot/iotDeviceLinkageTriggerApi.js'
	import {
		formatSensorType
	} from '@/util/dataUtil.js'
	const hours = [];
	const minutes = [];
	const thours = [];
	const tminutes = [];
	for (let i = 0; i < 24; i++) {
		let n = i + ''
		hours[i] = n[1] ? n : '0' + n
	}
	for (let i = 0; i < 60; i++) {
		let n = i + ''
		minutes[i] = n[1] ? n : '0' + n
	}
	for (let i = 0; i < 24; i++) {
		let n = i + ''
		thours[i] = n[1] ? n : '0' + n
	}
	for (let i = 0; i < 60; i++) {
		let n = i + ''
		tminutes[i] = n[1] ? n : '0' + n
	}

	export default {
		name: 'LinkageTrigger',
		props: {
			linkage: {
				type: Object,
				default: null
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		data() {
			return {
				trigger: {},
				triggerList: [],
				sensorList: [],
				logicList: [],
				editDialog: false,
				typeList: [],
				timeSlotMultiArray: [hours, minutes, thours, tminutes],
				timeSlotMultiIndex: [0, 0, 0, 0],
				explainMultiIndex: [0, 0],
				explainMultiArray: [],
				isEdit: false,
				haveChange: false
			}
		},
		created() {
			this.logicList = [{
					label: this.$t('greater'),
					value: '>'
				},
				{
					label: this.$t('equal'),
					value: '='
				},
				{
					label: this.$t('less'),
					value: '<'
				},
			]
			this.typeList = [{
				label: this.$t('time'),
				value: 't'
			}, {
				label: this.$t('timeSlot'),
				value: 't2'
			}, {
				label: this.$t('interval'),
				value: 'i'
			}, {
				label: this.$t('sensor'),
				value: 's'
			}, ]
			this.listSensorWithExplain()
		},
		methods: {
			formatSensorType(type) {
				return formatSensorType(this, type)
			},
			sensorChange(i) {
				const explainList = []
				const sensor = this.sensorList[i]
				for (const expalin of sensor.explainList) {
					explainList.push(expalin.name)
				}
				this.explainMultiArray.splice(1, 1, explainList)
			},
			timerChange(e) {
				this.trigger.timer = e.detail.value
			},
			timerSlotChange(e) {
				const index = e.detail.value;
				const hour = this.timeSlotMultiArray[0][index[0]]
				const minute = this.timeSlotMultiArray[1][index[1]]
				const thour = this.timeSlotMultiArray[2][index[2]]
				const tminute = this.timeSlotMultiArray[3][index[3]]
				this.trigger.timer = hour + ':' + minute + ' / ' + thour + ':' + tminute
			},
			explainMultiChange(e) {
				this.explainMultiIndex = e.detail.value
			},
			explainMultiColumnChange(e) {
				if (e.detail.column === 0) {
					this.sensorChange(e.detail.value)
				}
			},
			logicChange(item) {
				this.trigger.logic = item.value
			},
			typeChange(item) {
				switch (item.value) {
					case 't':
					case 'i':
						this.trigger.timer = '00:00'
						break
					case 't2':
						this.trigger.timer = '00:00 / 00:00'
						this.timeSlotMultiIndex = [0, 0, 0, 0]
						break
					case 's':
						this.trigger.port = '0'
						this.trigger.keyName = ''
						this.trigger.logic = '>'
						this.trigger.rawValue = ''
						this.sensorChange(0)
						this.explainMultiIndex = [0, 0]
						break
					default:
						showToast(this.$t('failure'), 'none', 1000, false) //操作失败
				}
				this.trigger.type = item.value
			},
			showAdd() {
				this.trigger = {
					type: 's',
					port: '',
					keyName: '',
					logic: '>',
					rawValue: '',
					value: '',
					timer: null,
					triggerId: 'a' + this.triggerList.length
				}
				this.explainMultiIndex = [0, 0]
				this.sensorChange(0)
				this.editDialog = true
				this.isEdit = false
			},
			edit(item) {
				switch (item.type) {
					case 't2':
						if (item.timer.indexOf(' / ') != -1) {
							const timeValue = item.timer.split(' / ');
							const fvalue = timeValue[0].split(':');
							const svalue = timeValue[1].split(':');
							this.timeSlotMultiIndex = fvalue.concat(svalue)
							// item.value = fvalue.map(this.formatNumber).join(':') + ' / ' + svalue.map(this.formatNumber).join(':')
						} else {
							this.timeSlotMultiIndex = [0, 0, 0, 0]
						}
						break
					case 's':
						const explainList = []
						for (const i in this.sensorList) {
							const sensor = this.sensorList[i]
							if (item.port === sensor.port) {
								for (const expalin of sensor.explainList) {
									explainList.push(expalin.name)
								}
								this.explainMultiArray[1] = explainList
								for (const j in sensor.explainList) {
									const explain = sensor.explainList[j]
									if (explain.keyName === item.keyName) {
										this.explainMultiIndex = [i, j]
										break
									}
								}
								break
							}
						}
						break
				}
				this.trigger = item
				this.editDialog = true
				this.isEdit = true
			},
			editSave() {
				switch (this.trigger.type) {
					case 's':
						const sensor = this.sensorList[this.explainMultiIndex[0]]
						this.trigger.port = sensor.port
						this.trigger.keyName = sensor.explainList[this.explainMultiIndex[1]].keyName
						break
				}
				if (this.isEdit) {
					for (const i in this.triggerList) {
						const trigger = this.triggerList[i]
						if (trigger.triggerId === this.trigger.triggerId) {
							this.triggerList.splice(i, 1, this.formatterTrigger(this.trigger))
							break
						}
					}
				} else {
					this.triggerList.push(this.formatterTrigger(this.trigger))
				}
				this.editDialog = false
				this.haveChange = true
			},
			save() {
				if (this.linkage.type === 'device') {
					deviceLinkageTriggerApi.insertOrUpdateLinkageTriggerToDevice({
						linkageId: this.linkage.linkageId,
						triggerList: this.triggerList
					}).then(res => {
						const {
							data
						} = res
						if (data) {
							this.haveChange = false
						} else {
							showToast(this.$t('failure'), 'none', 1000, false)
						}
						this.listLinkageTrigger()
					})
				} else if (this.linkage.type === 'server') {
					deviceLinkageTriggerApi.insertOrUpdateLinkageTriggerToServer({
						linkageId: this.linkage.linkageId,
						triggerList: this.triggerList
					}).then(res => {
						const {
							data
						} = res
						if (data) {
							this.haveChange = false
						} else {
							showToast(this.$t('failure'), 'none', 1000, false)
						}
						this.listLinkageTrigger()
					})
				} else {
					showToast(this.$t('failure'), 'none', 1000, false) //操作失败
				}
			},
			deleteItem(index) {
				this.triggerList.splice(index, 1)
				this.haveChange = true
			},
			formatterLogic(logic) {
				for (const item of this.logicList) {
					if (item.value === logic) {
						return item.label
					}
				}
			},
			formatterTrigger(trigger) {
				if (trigger.type === 's') {
					for (const sensor of this.sensorList) {
						if (sensor.port === trigger.port) {
							for (const explain of sensor.explainList) {
								if (trigger.keyName === explain.keyName) {
									trigger.name = explain.name
									trigger.iconUrl = explain.iconUrl
									trigger.sensorName = sensor.sensorName
									trigger.sensorType = sensor.type
									return trigger
								}
							}
						}
					}
				}
				return trigger
			},
			listLinkageTrigger() {
				deviceLinkageTriggerApi.listLinkageTrigger({
					linkageId: this.linkage.linkageId
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						const triggerList = []
						for (const trigger of data) {
							triggerList.push(this.formatterTrigger(trigger))
						}
						this.triggerList = triggerList
					}
				})
			},
			formatNumber(n) {
				n = n.toString()
				return n[1] ? n : '0' + n
			},
			listSensorWithExplain() {
				deviceSensorApi.listSensorWith({
					deviceId: this.linkage.deviceId,
					withExplain: true
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						const sensorList = []
						const sensorNameList = []
						for (const sensor of data) {
							if (sensor.explainList && sensor.explainList.length > 0) {
								sensorNameList.push(this.formatSensorType(sensor.type) + this.$t('port') + ':' +
									sensor.port + ' ' + sensor.sensorName)
								sensorList.push(sensor)
							}
						}
						this.explainMultiArray[0] = sensorNameList
						this.sensorList = sensorList
						this.sensorChange(0)
					} else {
						this.sensorList = []
					}
					this.listLinkageTrigger()
				})
			},
		}
	}
</script>
<style>
</style>
